package com.expert.miniapp.controller;

import com.expert.miniapp.dto.ResultDTO;
import com.expert.miniapp.dao.Instrument;
import com.expert.miniapp.dao.InstrumentMapper;
import com.expert.miniapp.service.InstrumentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 仪器设备控制器
 * 提供仪器设备相关的REST API接口
 */
@RestController
@RequestMapping("/api/instruments")
@CrossOrigin(origins = "*")
public class InstrumentController {

    @Autowired
    private InstrumentService instrumentService;

    @Autowired
    private InstrumentMapper instrumentMapper;

    /**
     * 根据ID获取仪器设备详情
     * @param id 仪器设备ID
     * @return 仪器设备详情
     */
    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResultDTO<Instrument> getInstrumentDetails(@PathVariable String id) {
        try {
            Instrument instrument = instrumentService.getInstrumentById(id);
            if (instrument != null) {
                return ResultDTO.success(instrument);
            } else {
                return ResultDTO.error("仪器设备不存在");
            }
        } catch (Exception e) {
            return ResultDTO.error("查询仪器设备失败: " + e.getMessage());
        }
    }

    /**
     * 获取仪器设备列表（支持分页、分类筛选、权重推荐、模糊搜索）
     * @param pageNum 页码（可选）
     * @param pageSize 每页数量（可选）
     * @param category 分类（可选）
     * @param sortBy 排序方式，weight表示按权重推荐（可选）
     * @param keyword 搜索关键词（可选）
     * @return 仪器设备列表
     */
    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResultDTO<PageInfo<Instrument>> getInstrumentList(
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String keyword) {
        try {
            PageInfo<Instrument> pageInfo;

            if (keyword != null && !keyword.trim().isEmpty()) {
                pageInfo = instrumentService.searchInstruments(keyword, pageNum, pageSize);
            } else if ("weight".equalsIgnoreCase(sortBy)) {
                pageInfo = instrumentService.getRecommendedInstruments(pageNum, pageSize);
            } else if (category != null && !category.trim().isEmpty()) {
                pageInfo = new PageInfo<>(instrumentService.getInstrumentsByCategory(category));
            } else {
                pageInfo = instrumentService.getAllInstruments(pageNum, pageSize);
            }

            return ResultDTO.success(pageInfo);
        } catch (Exception e) {
            return ResultDTO.error("查询仪器设备列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据分类统计仪器设备数量
     * @param category 分类名称（如："人工智能"）
     * @return 包含该分类的仪器设备数量
     */
    @GetMapping(value = "/categories/statistics", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResultDTO<Map<String, Integer>> getCountByCategory(@RequestParam String category) {
        try {
            Integer count = instrumentMapper.countByCategory(category);
            Map<String, Integer> result = new HashMap<>();
            result.put("count", count != null ? count : 0);
            return ResultDTO.success(result);
        } catch (Exception e) {
            return ResultDTO.error("统计仪器设备数量失败: " + e.getMessage());
        }
    }
}